//
//  FillViewController.m
//  DaDaBao
//
//  Created by admin on 15/8/18.
//  Copyright (c) 2015年 User. All rights reserved.
//

#import "FillViewController.h"
#import "CustomTextField.h"
#import "CardDetailViewController.h"

@interface FillViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
@property(nonatomic,strong)UITableView      *tableview;
@property(nonatomic,strong)NSArray          *dataArr;
@property(nonatomic,assign)BOOL             isAgreed;
@property(nonatomic,strong)UIButton         *nextBtn;
@property(nonatomic,strong)CustomTextField  *depositText;//开户行名字
@property(nonatomic,strong)CustomTextField  *cardText;//银行卡卡号
@property(nonatomic,strong)CustomTextField  *provinceText;//开户省
@property(nonatomic,strong)CustomTextField  *cityText;//开户城市
@property(nonatomic,strong)CustomTextField  *bankText;//银行名字
@property(nonatomic,strong)UILabel          *nameLab;


@end

@implementation FillViewController
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloginView) name:@"reLogin" object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
    
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self
                                                   name:@"reLogin"
                                                 object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self
                                                   name:@"UITextFieldTextDidChangeNotification"
                                                 object:_provinceText];
    [[NSNotificationCenter defaultCenter]removeObserver:self
                                                   name:@"UITextFieldTextDidChangeNotification"
                                                 object:_cityText];
    [[NSNotificationCenter defaultCenter]removeObserver:self
                                                   name:@"UITextFieldTextDidChangeNotification"
                                                 object:_bankText];
    [[NSNotificationCenter defaultCenter]removeObserver:self
                                                   name:@"UITextFieldTextDidChangeNotification"
                                                 object:_depositText];

    [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
}
-(void)reloginView
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"登录失败，请重新登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}
#pragma mark ----------------alertDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [AppGlobalClass exitLogin];
    
    LoginViewController *loginViewCon = [[LoginViewController alloc]init];
    [self presentViewController:loginViewCon animated:TRUE completion:^{}];
    
    NSArray *listArray = self.navigationController.viewControllers;
    
    id tabBar = [listArray objectAtIndex:1];
    if([[tabBar class] isSubclassOfClass:[UITabBarController class]])
    {
        UITabBarController *tabBarCon = tabBar;
        tabBarCon.selectedIndex = 0;
        [self.navigationController popToViewController:[listArray objectAtIndex:1] animated:TRUE];
    }
    else
    {
        UITabBarController *tabBarCon = [listArray objectAtIndex:2];
        tabBarCon.selectedIndex = 0;
        [self.navigationController popToViewController:[listArray objectAtIndex:2] animated:TRUE];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor hexStringToColor:@"#ebebeb"];
    _dataArr = @[@"持卡人",@"银行名称",@"开户行省份",@"开户行城市",@"开户行名称",@"银行卡卡号"];
    [self createUI];
    
    
}
-(void)createUI
{
    TopView *topView =[[TopView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:@"添加银行卡"];
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0.0f, 20.0f, 64.0f, 44.0f)];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(buttonBackTapped:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:backBtn];

    [self.view addSubview:topView];
    
    UIScrollView *bgScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f, 64.0f, SCREEN_WIDTH, SCREEN_HEIGHT)];
    bgScroll.backgroundColor = [UIColor hexStringToColor:@"#ebebeb"];
    bgScroll.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT+100.0f);
    bgScroll.showsVerticalScrollIndicator = FALSE;
    [self.view addSubview:bgScroll];

    if (!_tableview) {
        _tableview = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 10.0f, SCREEN_WIDTH, 44.0f*_dataArr.count) style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.bounces = FALSE;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        [bgScroll addSubview:_tableview];

    }
    //    边缘线
    UILabel *sepLab = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, _tableview.frame.origin.y-0.1f, SCREEN_WIDTH, 0.5f)];
    sepLab.backgroundColor = [UIColor lightGrayColor];
    [bgScroll addSubview:sepLab];
    
    _nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _nextBtn.frame = CGRectMake(10.0f, 44.0f*_dataArr.count+40.0f, SCREEN_WIDTH-20.0f, 35.0f*HSCALE);
    [_nextBtn setBackgroundColor:[UIColor hexStringToColor:RED_COLOR_VALUE]];
    [_nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    _nextBtn.layer.cornerRadius = 5.0f;
    [_nextBtn addTarget:self action:@selector(buttonNextTapped:) forControlEvents:UIControlEventTouchUpInside];
    [bgScroll addSubview:_nextBtn];
    
}
//银行
-(CustomTextField *)bankText
{
    if (!_bankText) {
        _bankText= [[CustomTextField alloc] initWithFrame:CGRectMake(100.0f, 13.0f, SCREEN_WIDTH-110.0f, 22.0f)];
        _bankText.placeholder=@"请输入银行名称";
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)
                                                    name:@"UITextFieldTextDidChangeNotification" object:_bankText];
        [_bankText setValue:[UIFont boldSystemFontOfSize:14.0f] forKeyPath:@"_placeholderLabel.font"];
        

    }
    return _bankText;
}
//城市
-(CustomTextField *)cityText
{
    if (!_cityText) {
        _cityText= [[CustomTextField alloc] initWithFrame:CGRectMake(110.0f, 13.0f, SCREEN_WIDTH-110.0f, 22.0f)];
        _cityText.placeholder=@"请输入城市";
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(cityEditChanged:)
                                                    name:@"UITextFieldTextDidChangeNotification" object:_cityText];

        [_cityText setValue:[UIFont boldSystemFontOfSize:14.0f] forKeyPath:@"_placeholderLabel.font"];
        
        
    }
    return _cityText;
}
//开户行
-(CustomTextField *)depositText
{
    if (!_depositText) {
        _depositText= [[CustomTextField alloc] initWithFrame:CGRectMake(110.0f, 13.0f, SCREEN_WIDTH-110.0f, 22.0f)];
        _depositText.placeholder=@"请输入开户行名称";
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(depositEditChanged:)
                                                    name:@"UITextFieldTextDidChangeNotification" object:_depositText];

        [_depositText setValue:[UIFont boldSystemFontOfSize:14.0f] forKeyPath:@"_placeholderLabel.font"];
        
        
    }
    return _depositText;
}
//卡号
-(CustomTextField *)cardText
{
    if (!_cardText) {
        _cardText= [[CustomTextField alloc] initWithFrame:CGRectMake(110.0f, 13.0f, SCREEN_WIDTH-110.0f, 22.0f)];
        _cardText.placeholder=@"请输入银行卡卡号";
        _cardText.keyboardType = UIKeyboardTypeNumberPad;
        [_cardText setValue:[UIFont boldSystemFontOfSize:14.0f] forKeyPath:@"_placeholderLabel.font"];
        
        
    }
    return _cardText;
}
//省份
-(CustomTextField *)provinceText
{
    if (!_provinceText) {
        _provinceText= [[CustomTextField alloc] initWithFrame:CGRectMake(110.0f, 13.0f, SCREEN_WIDTH-110.0f, 22.0f)];
        _provinceText.placeholder=@"请输入省份";
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(cityEditChanged:)
                                                    name:@"UITextFieldTextDidChangeNotification" object:_provinceText];

        [_provinceText setValue:[UIFont boldSystemFontOfSize:14.0f] forKeyPath:@"_placeholderLabel.font"];
        
        
    }
    return _provinceText;
}
-(UILabel *)nameLab
{
    if (!_nameLab) {
        _nameLab = [[UILabel alloc] initWithFrame:CGRectMake(100.0f, 10.0f, SCREEN_WIDTH - 110.0f, 24.0f)];
        _nameLab.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"realName"];
    }
    return _nameLab;
}
#pragma mark- tableViewDatasource &delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        UILabel *sepLab = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 43.5f, SCREEN_WIDTH, 0.5f)];
        sepLab.backgroundColor = [UIColor blackColor];
        [cell addSubview:sepLab];
        
        
    }
    cell.textLabel.text = [_dataArr objectAtIndex:indexPath.row];
    switch (indexPath.row) {
        case 0:
        {
            [cell addSubview:self.nameLab];
        }
            break;
        case 1:
        {
             [cell addSubview:self.bankText];
        }
            break;
        case 2:
        {
            [cell addSubview:self.provinceText];
        }
            break;
        case 3:
        {
            [cell addSubview:self.cityText];
        }
            break;
        case 4:
        {
            [cell addSubview:self.depositText];
        }
            break;
        case 5:
        {
            [cell addSubview:self.cardText];
        }
            break;

        default:
            break;
    }
    
    return cell;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark-限制长度
-(void)textFiledEditChanged:(NSNotification *)obj
{
    UITextField *textField = (UITextField *)obj.object;
    NSString *toBeString = textField.text;
    NSString * lang=[[[UIApplication sharedApplication]textInputMode] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > 20) {
                textField.text = [toBeString substringToIndex:20];
            }
        }
      }
    else{
        if (toBeString.length > 20) {
            textField.text = [toBeString substringToIndex:20];
        }
    }
 }
-(void)cityEditChanged:(NSNotification *)obj
{
    UITextField *textField = (UITextField *)obj.object;
    NSString *toBeString = textField.text;
    NSString * lang=[[[UIApplication sharedApplication]textInputMode] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > 8) {
                textField.text = [toBeString substringToIndex:8];
            }
        }
    }
    else{
        if (toBeString.length > 8) {
            textField.text = [toBeString substringToIndex:8];
        }
    }
}
-(void)depositEditChanged:(NSNotification *)obj
{
    UITextField *textField = (UITextField *)obj.object;
    NSString *toBeString = textField.text;
    NSString * lang=[[[UIApplication sharedApplication]textInputMode] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > 32) {
                textField.text = [toBeString substringToIndex:32];
            }
        }
    }
    else{
        if (toBeString.length > 32) {
            textField.text = [toBeString substringToIndex:32];
        }
    }

}

#pragma mark-下一步
-(void)buttonNextTapped:(id)sender
{
//    判断
    BOOL isCardNum  = [self.cardText checkCardNum:_cardText.text];

    if (self.bankText.text.length == 0)
    {
        ALERT_VIEW(@"银行名称不能为空");
    }
     else if(self.provinceText.text.length == 0)
    {
        ALERT_VIEW(@"开户行省份不能为空");
    }
      else if (self.cityText.text.length == 0)
    {
        ALERT_VIEW(@"开户行城市不能为空");
    }
    else if (self.depositText.text.length == 0)
    {
        ALERT_VIEW(@"开户行名称不能为空");
    }
    else if (self.cardText.text.length == 0)
    {
        ALERT_VIEW(@"银行卡卡号不能为空");
    }
    else if (!isCardNum)
    {
        ALERT_VIEW(@"银行卡号错误");
    }
    else
    {
       [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];

       NSDictionary *dict = @{ @"token":[[NSUserDefaults standardUserDefaults]objectForKey:@"token"], @"accountNo":_cardText.text, @"accountName":[[NSUserDefaults standardUserDefaults]objectForKey:@"realName"], @"accountType":[NSNumber numberWithInt:1], @"bankName":_bankText.text,@"bankProvince":_provinceText.text,@"bankCity":_cityText.text,@"bankBranchName":_depositText.text};
       
       [AppGlobalClass PostDataWithNSstring:BIND_CARD_URL withDictionary:dict success:^(NSDictionary *dictionary){
           
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            
            NSString * bankName = [[[[[dictionary objectForKey:@"responseData"] firstObject]objectForKey:@"rows"]firstObject] objectForKey:@"bankName"] ;
        
            CardDetailViewController *cardDetailViewCon = [[CardDetailViewController alloc]initWithCardId:_cardText.text andTheBankName:bankName];
            [self.navigationController pushViewController:cardDetailViewCon animated:TRUE];
            [[NSUserDefaults standardUserDefaults]setObject:[NSNumber numberWithInt:1] forKey:@"cardVStatus"];
        }

        else
        {
            ALERT_VIEW([dictionary objectForKey:@"message"]);
        }
           [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];

       } failure:^(NSError *error){
           [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
} networkerror:^(NSString *networkstring){
    [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
}];
   }

}
#pragma mark-返回上一页
-(void)buttonBackTapped:(id)sender
{
    [self.navigationController popViewControllerAnimated:TRUE];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:TRUE];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
